<?php

trait Trait_Api_Hotel
{

    /**
     * 单酒店获取酒店详情
     * @param $params
     * @return array
     * @throws Kohana_Exception
     * User: netman
     * Date: 2023/9/12 9:20
     */
    public function get_hotel_by_order($params)
    {
        $hotel = $this->get_index_recommend(1,$params['platform_no']);
        $params['id'] = $hotel[0]['id'];
        $data = $this->info($params);
        if (empty($data)) {
            throw new Exception('查询酒店失败');
        }
        return $data;
    }


    // 获取游客信息是否开启
    public function get_tourer_config()
    {
        $data = Model_Sysconfig::get_one_config('cfg_plugin_hotel_usetourer');
        unset($data['id'], $data['webid'], $data['info']);
        return $data;
    }

    /**
     * 按目的地获取酒店
     * @param $dest_id
     * @param $page
     * @param $pagesize
     * @return array|mixed
     * User: netman
     * Date: 2023/9/11 18:02
     */
    public function get_hotel_list_by_dest($dest_id, $page, $pagesize,$platform_no)
    {

        $fields = [
            'hotel.id',
            'hotel.sellpoint',
            'hotel.title',
            'hotel.litpic',
            'hotel.price',
            'hotel.satisfyscore',
            'hotel.attrid',
            'hotel.iconlist',
            'hotel.hotelrankid',
        ];
        $result = DB::select_array($fields)->from('hotel')->join('kindorderlist', 'LEFT')
            ->on('hotel.id', '=', 'kindorderlist.aid')
            ->on('kindorderlist.classid','=',(int)$dest_id)
            ->on('kindorderlist.typeid', '=', self::TYPE_ID)
            ->and_where('hotel.status','=',3)
            ->and_where(DB::expr(" and FIND_IN_SET({$platform_no},sline_hotel.platform)"))
            ->and_where(DB::expr(" and FIND_IN_SET({$dest_id},sline_hotel.kindlist)"))
            ->order_by(DB::expr("IFNULL(sline_kindorderlist.displayorder,9999)"), 'asc')
            ->order_by('hotel.modtime', 'desc')
            ->order_by('hotel.addtime', 'desc')
            ->limit($pagesize)
            ->execute()
            ->as_array();
        $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID);
        foreach ($result as &$item) {
            if(isset($uni_img[$item['id']])){
                $item['litpic'] = $this->img_url($uni_img[$item['id']], 342, 342);
            }else{
                $item['litpic'] = $this->img_url($item['litpic'], 342, 342);
            }
            $item['price'] = $item['price'] ?? Model_Hotel::get_minprice($item['id']);
            $item['sellprice'] = Model_Hotel::get_sellprice($item['id']);//挂牌价
            $item['attrlist']   = Model_Hotel_Attr::get_attr_list($item['attrid']);
            $item['commentnum'] = Model_Comment::get_comment_num($item['id'], self::TYPE_ID);
            $item['rank_name'] = $this->get_rank_name($item['hotelrankid']);
            $item['icon_list'] = Product::get_ico_list($item['iconlist']);
        }
        return $result;
    }

    /**
     * 获取星级和价格
     * @return array
     * User: netman
     * Date: 2023/9/11 18:05
     */
    public function get_rand_and_price()
    {
        $data = array();
        //星级
        $data['star']['child'] = $this->get_ranks();
        //价格
        $data['price']['child'] = $this->get_prices();

        return $data;
    }


    /**
     * 获取首页推荐
     * @param $pagesize
     * @return array|mixed
     * User: netman
     * Date: 2023/9/12 9:29
     */
    public function get_index_recommend($pagesize,$platform_no)
    {

        $fields = [
            'hotel.id',
            'hotel.sellpoint',
            'hotel.title',
            'hotel.litpic',
            'hotel.price'
        ];
        $result = DB::select_array($fields)->from('hotel')->join('allorderlist', 'LEFT')
            ->on('hotel.id', '=', 'allorderlist.aid')
            ->on('allorderlist.typeid', '=', self::TYPE_ID)
            ->and_where('hotel.status','=',3)
            ->and_where(DB::expr(" and FIND_IN_SET({$platform_no},sline_hotel.platform)"))
            ->order_by(DB::expr("IFNULL(sline_allorderlist.displayorder,9999)"), 'asc')
            ->order_by('hotel.addtime', 'desc')
            ->limit($pagesize)
            ->execute()
            ->as_array();
        $uni_img = Model_Uniapp_Images::get_img_list(2);
        foreach ($result as &$item) {
            if(isset($uni_img[$item['id']])){
                $item['litpic'] = $this->img_url($uni_img[$item['id']], 300, 300);
            }else{
                $item['litpic'] = $this->img_url($item['litpic'], 300, 300);
            }
            $item['price'] = $item['price'] ?? Model_Hotel::get_minprice($item['id']);
        }
        return $result;
    }



    /**
     * 根据日期获得该酒店套餐列表
     * @param $params
     * @return array
     * User: netman
     * Date: 2023/9/12 9:43
     */
    public function get_suit_list_by_day($params)
    {
        $day_num     = $params['day'];
        $hotel_id    = $params['hotel_id'];
        $start_time  = $params['start_time'];
        $end_time    = $params['end_time'];

        $single_hotel = abs((int)$params['single_hotel']);
        $card_suit_id = $params['card_suit_id'];//会员卡关联的套餐id
        $is_seckill   = $params['is_seckill'];

        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);
        //秒杀
        if ($is_seckill) {
            $data = Model_Seckill::get_suitlist_by_hotelid($hotel_id, $start_time, $end_time, $day_num, $is_seckill);
        } else {
            $data = Model_Hotel_Room::get_suitlist_by_hotelid($hotel_id, $start_time, $end_time, $day_num, $card_suit_id);
        }

        $time = time();
        if (!empty($data)) {
            $cservicelist = $this->get_services('room');
            $refund_class = Service_Refund_Rule_Factory::get_instance(self::TYPE_ID);
            foreach ($data as $ke => $v) {
                // 获取房型时间区间最低价
                $price              = $this->get_room_mini_price($v['id'], $start_time, $end_time);
                $data[$ke]['price'] = Currency_Tool::price($price);
                if ($single_hotel == 1) {
                    $data[$ke]['discount_min_price'] = Model_Api_V2_Discount::get_discount_new($params['mid'], self::TYPE_ID, $hotel_id, $price);
                } else {
                    $data[$ke]['discount_min_price'] = Model_Api_V2_Discount::get_discount($params['mid'], self::TYPE_ID, $hotel_id, $price);
                }
                $pic_list = array();
                if (!empty($v['piclist'])) {
                    foreach ($v['piclist'] as $vp) {
                        $pic_list[] = $this->img_url($vp[0]);
                    }
                }
                $data[$ke]['piclist'] = $pic_list;
                $data[$ke]['litpic']      = $this->img_url($v['litpic'], 750, 400);
                $data[$ke]['description'] = $this->content_add_domain($data[$ke]['description']);
                //设施列表
                if (!empty($v['servicelist'])) {
                    $carray   = $cservicelist;
                    $csc      = explode(",", $v['servicelist']);
                    $trcarray = array();
                    foreach ($carray as $velc) {
                        if (!empty($velc['children'])) {
                            foreach ($velc['children'] as $keyvc => $velvc) {
                                if (in_array($velvc['id'], $csc)) {
                                    $velc['children'][$keyvc]['isshow'] = true;
                                } else {
                                    $velc['children'][$keyvc]['isshow'] = false;
                                }
                            }
                        }
                        array_push($trcarray, $velc);
                    }
                    $data[$ke]['servicelistdetail'] = $trcarray;
                }

                //可以预订的时间
                $data[$ke]['book_time'] = '';
                if ($v['day_before'] == 0) {
                    // 小时分钟均为00时，表示可以在23：59：59秒前预订
                    if ($v['hour_before'] == 0) {
                        $v['hour_before']   = 23;
                        $v['minute_before'] = 59;
                    }
                    $data[$ke]['book_time'] = $time < strtotime(date('Y-m-d') . " {$v['hour_before']}:" . ($v['minute_before'] ? $v['minute_before'] : '00')) ? '' : (strtotime(date('Y-m-d')) + 3600 * 24);
                } elseif ($v['day_before'] == 1) {

                    if ($time < strtotime(date('Y-m-d') . " {$v['hour_before']}:" . ($v['minute_before'] ? $v['minute_before'] : '00')) || !$v['hour_before']) {
                        $data[$ke]['book_time'] = (strtotime(date('Y-m-d')) + 3600 * 24);
                    } else {
                        $data[$ke]['book_time'] = (strtotime(date('Y-m-d')) + 3600 * 24 * 2);
                    }
                } elseif ($v['day_before'] > 1) {
                    if ($time < strtotime(date('Y-m-d') . " {$v['hour_before']}:" . ($v['minute_before'] ? $v['minute_before'] : '00')) || !$v['hour_before']) {
                        $data[$ke]['book_time'] = (strtotime(date('Y-m-d')) + 3600 * 24 * $v['day_before']);
                    } else {
                        $data[$ke]['book_time'] = (strtotime(date('Y-m-d')) + 3600 * 24 * ($v['day_before'] + 1));
                    }
                }
                $data[$ke]['book_time_date'] = $data[$ke]['book_time'] ? date('Y-m-d', $data[$ke]['book_time']) : '';

                // 套餐退款规则
                $data[$ke]['refund_rule']  = $refund_class->get_format_refund_rule($v['id']);
                $data[$ke]['refund_restriction_name']  = $refund_class->get_refund_restriction_name($v['refund_restriction']);

                //剔除不能预定的
                if (!empty($data[$ke]['book_time']) && $data[$ke]['book_time'] > strtotime(date('Y-m-d 23:59:59', $start_time))) {
                    unset($data[$ke]);
                }
            }
        }
        return $data;

    }

    /**
     * 获取日历每天报价
     * @param $params
     * @return array|array[]|mixed
     * User: netman
     * Date: 2023/9/12 9:48
     */
    public function get_everyday_price($params)
    {
        $suit_id     = $params['suit_id'];
        $row         = $params['row'];
        $start_time  = $params['start_time'];
        $end_time    = $params['end_time'];
        $seckill_id  = $params['is_seckill'];
        $together_id = $params['together_id'];
        // 拼团
        if ($together_id) {
            $params    = array(
                'start_time' => $start_time,
                'end_time' => $end_time,
                'row' => $row,
                'member_id' => $params['mid']
            );
            $base_data = Model_Api_V2_Together::get_price_calendar($together_id, $params);
            $base_data = $this->make_day_price($base_data);
        } else if ($seckill_id) { //秒杀
            $base_data = Model_Seckill::get_hotel_day_price($suit_id, $seckill_id, $row);
            $base_data = Model_Seckill::hotel_day_each($base_data, $seckill_id);
        } else {
            $base_data = $this->get_day_price($suit_id, $start_time, $end_time, $row);
            $base_data = $this->make_day_price($base_data);
        }

        // 格式化返回数据
        if ($base_data) {
            $base_data = $this->format_day_price($base_data);
        }
        return $base_data;
    }

    /**
     * 获取房型列表
     * @param $hotel_id
     * @param $suit_id
     * @param $seckill_id
     * @return mixed|null
     * @throws Exception
     * User: netman
     * Date: 2023/9/12 9:51
     */
    public function get_room_detail($hotel_id, $suit_id, $seckill_id)
    {
        $hotel =  $this->get_hotel($hotel_id, 'title,aid');
        if(!$hotel)
        {
            throw new Exception('酒店不存在');
        }
        $fields = [
            'id',
            'hotelid',
            'roomname',
            'breakfirst',
            'computer',
            'roomstyle',
            'roomarea',
            'roomfloor',
            'roomwindow',
            'piclist',
            'jifencomment',
            'jifentprice',
            'jifenbook',
            'paytype',
            'dingjin',
            'description',
            'need_confirm',
            'pay_way',
            'auto_close_time',
            'limit_order',
            'litpic',
            'servicelist',
            'day_before',
            'hour_before',
            'minute_before',
            'refund_restriction',
            'people_limit',
            'bed_addable',
            'auto_confirm_time'
        ];
        $hotel_room = DB::select_array($fields)
            ->from('hotel_room')
            ->where('id', '=', $suit_id)
            ->execute()
            ->current();
        if(!$hotel_room )
        {
            throw new Exception('房型不存在');
        }

        /*存在就将价格替换为秒杀价*/
        if ($seckill_id) {
            $seckill = DB::select()
                ->from('seckill')
                ->where('id', '=', $seckill_id)
                ->execute()
                ->current();
            if (!$seckill) {
                throw new Exception('秒杀不存在');
            }

            $hotel_room['pay_way']     = 1;
            $hotel_room['limit_order'] = $seckill['purchase_limits'] > 0 && $seckill['purchase_limits'] < $seckill['number'] ? $seckill['purchase_limits'] : $seckill['number'];//库存;
            $hotel_room['description'] = $seckill['describe'];
            $hotel_room['bed_addable'] = 0;
        }

        $refund_class = Service_Refund_Rule_Factory::get_instance(self::TYPE_ID);
        $hotel_room['productname'] = $hotel['title'];
        $hotel_room['productaid']  = $hotel['aid'];
        $hotel_room['title']       = $hotel_room['roomname'];
        $hotel_room['piclist']     = Model_Api_V2_System::get_product_piclist($hotel_room['piclist']);
        $hotel_room['refund_rule'] = $refund_class->get_format_refund_rule($suit_id);
        $hotel_room['refund_restriction_name'] = $refund_class->get_refund_restriction_name($hotel_room['refund_restriction']);
        $hotel_room['paytype_name'] = Model_Member_Order::get_paytype_name($hotel_room['paytype']);
        return $hotel_room;
    }

    /**
     * 热门酒店属性
     * User: netman
     * Date: 2023/9/12 9:53
     */
    public function get_hotel_attr()
    {
        $attr = DB::select('attrid')->from('hotel')
            ->where('attrid','!=', '')
            ->execute()
            ->as_array();
        $attr_id = array();
        foreach ($attr as $v){
            $arr = explode(',',$v['attrid']);
            $attr_id = array_merge($arr,$attr_id);
        }
        $attr_id = array_filter($attr_id, function($value) {
            return $value != 0;
        });
        $counted = array_count_values($attr_id);
        // 按值出现次数降序排序
        arsort($counted);
        // 取出前10个重复次数最多属性id
        $top10 = array_slice(array_keys($counted), 0, 10);

        if(count($top10)>0){
            $top10_str = implode(',',$top10);
            $attr_list = DB::select('id','attrname')
                ->from('hotel_attr')
                ->where('id', 'in', $top10)
                ->where("pid",'>',0)
                ->order_by(DB::expr("FIELD(id, {$top10_str})"))
                ->execute()
                ->as_array();
            $attr_list = array_merge(array(array('id'=>0,'attrname'=>'全部')),$attr_list);
            $data = $attr_list;
        }else{
            $data = array();
        }
        return $data;
    }

    /**
     * 获取热门酒店
     * @param $page
     * @param $pagesize
     * @param $mid
     * @return array
     * User: netman
     * Date: 2023/9/12 14:33
     */
    public function get_hot_hotel($page, $pagesize, $mid,$platform_no)
    {
        $offset    = ($page - 1) * $pagesize;
        $hotel_list = DB::select('a.id', 'a.title', 'a.litpic', 'a.satisfyscore', 'a.sellpoint', 'a.attrid')
            ->from(array('hotel', 'a'))
            ->join(array('allorderlist', 'b'))
            ->on('a.id', '=', DB::expr('sline_b.aid'))
            ->on('b.typeid', '=', self::TYPE_ID)
            ->where(DB::expr(" FIND_IN_SET({$platform_no},sline_a.platform)"))
            ->and_where('a.status', '=', 3)
            ->order_by(DB::expr("IFNULL(sline_b.displayorder,9999) asc,sline_a.modtime desc,sline_a.addtime"))
            ->offset($offset)
            ->limit($pagesize)
            ->execute()
            ->as_array();

        foreach ($hotel_list as &$v) {
            $v['price']     = Model_Hotel::get_minprice($v['id'], array('info' => $v));
            $v['sellprice'] = Model_Hotel::get_sellprice($v['id']);//挂牌价
            if ($mid) {
                $v['discount_min_price'] = Model_Api_V2_Discount::get_discount($mid, self::TYPE_ID, $v['id'], $v['price']);
            } else {
                $v['discount_min_price'] = 0;
            }
            $v['attrlist']   = Model_Hotel_Attr::get_attr_list($v['attrid']);
            $v['litpic']     = $this->img_url($v['litpic'], 702, 334);
            $v['commentnum'] = Model_Comment::get_comment_num($v['id'], self::TYPE_ID);
        }
       return $hotel_list;
    }



    /*********************订单相关*************************/

    /**
     * 检查预订参数
     * @param $request_params
     * @return array
     * @throws Exception
     */
    private function check_order_params($request_params,$member_id)
    {
        $product_id = (int)($request_params['product_id']);
        $suit_id = (int)($request_params['suit_id']);
        $ding_num = (int)$request_params['ding_num'];

        // 检查秒杀活动限制
        $seckill_id = $request_params['seckill_id'] ?: 0;
        if ($seckill_id > 0) {
            if(St_Functions::is_normal_app_install('seckill'))
            {
                $status = Model_Seckill::get_seckill_num($seckill_id, $member_id);
                if (!$status) {
                    throw new Exception('已超出秒杀活动限制次数');
                }
            }
        }

        // 检查拼团或凑团限制
        $together_id = $request_params['together_id'] ?: 0;
        $join_id     = $request_params['join_id'] ?: 0;
        if ($together_id > 0 || $join_id > 0) {
            if(St_Functions::is_normal_app_install('together'))
            {
                $together_params      = array('join_id' => $join_id, 'ding_num'=> $ding_num);
                $check_order_together = Model_Api_V2_Together::check_order_together($together_id, $member_id, $together_params);
                if (!$check_order_together['status']) {
                    throw new Exception($check_order_together['msg']);
                }
                $together_info  = $check_order_together['data'];
                $together_price = $together_info['price'];
            }
        }

        //产品信息
        $info =  DB::select()
            ->from('hotel')
            ->where('id', '=', $product_id)
            ->execute()
            ->current();
        if (!$info) {
            throw new Exception('产品不存在');
        }

        //下架状态判断
        if ($info['status'] != 3) {
            throw new Exception('当前产品已下架，不可预订');
        }

        // 套餐信息
        $suit_info = Model_Hotel_Room::suit_info($suit_id);

        // 入住日期
        $use_date = $request_params['use_date'];
        // 离店日期
        $end_date = $request_params['end_date'];
        if (strtotime($use_date) >= strtotime($end_date)) {
            throw new Exception('离店日期需大于入住日期');
        }

        //限制日历房每天的可订购数量
        if($suit_info['limit_order']>0 ){
            $count_room = DB::select('id','departdate','usedate','dingnum')
                ->from('member_order')
                ->where('memberid','=',$member_id)
                ->where('suitid','=',$suit_id)
                ->where('typeid','=',2)
                ->execute()
                ->as_array();
            foreach ($count_room as  $count_room_v) {
                St_Functions::date_long($count_room_v['usedate'],$count_room_v['departdate'],$count_room_v['dingnum'],$suit_date_arr);
            }

            $limit_result = [];

            $suit_date_arr = array_map(function($item) use (&$limit_result) {
                $date = $item['date'];
                $num = $item['num'];
                if (isset($limit_result[$date])) {
                    $limit_result[$date]['num'] += $num;
                } else {
                    $limit_result[$date] = ['date' => $date, 'num' => $num];
                }
                return $item;
            }, $suit_date_arr);
            $limit_result = array_values($limit_result);

            St_Functions::date_long($use_date,$end_date,0,$date_long);

            foreach ($date_long as $date_long_v) {
                foreach ($limit_result as $limit_result_v) {
                    if ($date_long_v == $limit_result_v['date'] && ($ding_num + $limit_result_v['num']) > $suit_info['limit_order']) {
                        throw new Exception($limit_result_v['date'].' 限购：'.$suit_info['limit_order'].'，您已订购:'.$limit_result_v['num']);
                    }
                }
            }
        }

        //判断预定提前时间
        if ($suit_info['day_before'] > 0) {
            if (strtotime($use_date) < ($suit_info['day_before'] * 3600 * 24 + strtotime(date('Y-m-d')))) {
                throw new Exception('请提前' . $suit_info['day_before'] . '天预订');
            }
        } elseif ($suit_info['hour_before']) {
            if ($use_date == date('Y-m-d') && time() > strtotime(date('Y-m-d') . " {$suit_info['hour_before']}:{$suit_info['minute_before']}")) {
                throw new Exception("{$suit_info['hour_before']}:{$suit_info['minute_before']}" . '前结束当天预订');
            }
        }

        // 套餐报价
        $price = Model_Hotel::suit_range_price($suit_id, $use_date, $end_date, $ding_num);

        // 如果有拼团价就执行拼团价格
        if (isset($together_price)) {
            $price = St_Math::mul(array($together_price['adult_price'], $ding_num), 2);
            $price = Currency_Tool::price($price);
            $price = (float)$price;
        }

        $extend_data = array();
        if (isset($together_info)) {
            $extend_data['together_info'] = $together_info;
        }

        return array($info, $suit_info, $price, $extend_data);
    }

    /**
     *  创建订单信息
     * @param $request_params
     * @param $hotel
     * @param $hotel_room
     * @param $price
     * @param $extend_data
     * @return array
     */
    private  function make_order_data($request_params, $hotel, $hotel_room, $price, $extend_data)
    {
        $ordersn = St_Product::get_ordersn('02');
        $order   = array(
            'webid' => 0,
            'addtime' => time(),
            'typeid' => self::TYPE_ID,
            'ordersn' => $ordersn,
            'productautoid' => $hotel['id'],
            'suitid' => $hotel_room['id'],
            'suit_name' => $hotel_room['roomname'],
            'litpic' => $hotel['litpic'],
            'productaid' => $hotel['aid'],
            'productname' => $hotel['title'],
            'dingnum' => (int)($request_params['ding_num']),
            'paytype' => (int)($request_params['paytype']),
            'dingjin' => (int)($request_params['dingjin']),
            'usedate' => trim($request_params['use_date']),
            'departdate' => trim($request_params['end_date']),
            'linkman' => trim($request_params['linkman']),
            'linktel' => trim($request_params['linktel']),
            'linkemail' => $request_params['linkemail'],
            'remark' => $request_params['remark'],
        );

        // 自动关闭订单时间
        $auto_close_time = $hotel_room['auto_close_time'] ?: 0;
        if ($auto_close_time) {
            $order['auto_close_time'] = $auto_close_time + time();
        }

        // 待确认
        $order['need_confirm'] = isset($hotel_room['need_confirm']) ? $hotel_room['need_confirm'] : 0;

        $auto_confirm_time = $hotel_room['auto_confirm_time'] ?: 0;
        if ($auto_confirm_time) {
            $order['auto_confirm_time'] = $auto_confirm_time + time();
        }

        //自动退款时限
        $use_date=trim($request_params['use_date']);
        $no_confirm_refund = $hotel_room['no_confirm_refund'] ?: 0;
        if ($no_confirm_refund) {
            $order['no_confirm_refund'] = strtotime($use_date . ' +1 day') -  $no_confirm_refund ;
        }

        // 退款类型
        $order['refund_restriction'] = $hotel_room['refund_restriction'];

        // 订单状态
        $order['status'] = $order['need_confirm'] ? 0 : 1;

        // 订单来源 1PC,2WAP,3小程序,4平台添加
        $order['source'] = isset($request_params['source']) ? (int)($request_params['source']) : 3;

        // 支付方式
        $pay_way = $request_params['pay_way'];
        if ($pay_way) {
            $order['pay_way'] = $pay_way;
        }


        return $order;
    }

    /**
     * 积分抵现信息与评论送积分信息
     * @param $need_jifen
     * @param $hotel
     * @param $user_info
     * @return array
     * @throws Exception
     * User: netman
     * Date: 2023/9/13 16:35
     */
    private  function make_jifen_info($need_jifen, $hotel, $user_info)
    {

        $jifen_price = 0;
        $use_jifen   = 0;
        if ($need_jifen) {
            $jifen_price = Model_Jifen_Price::calculate_jifentprice($hotel['jifentprice_id'], self::TYPE_ID, $need_jifen, $user_info);
            $use_jifen   = empty($jifen_price) ? 0 : 1;
            $need_jifen  = empty($jifen_price) ? 0 : $need_jifen;
        }

        //积分评论
        $jifen_comment_info = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
        $jifen_comment      = empty($jifen_comment_info) ? 0 : $jifen_comment_info['value'];

        return compact('need_jifen', 'use_jifen', 'jifen_comment', 'jifen_price');
    }

    /*********************订单相关结束*************************/

    /*********************私有方法*************************/

    /**
     * 获取服务设施列表
     * @param $type
     * @return array
     */
    private  function get_services($type = "hotel")
    {
        $data = $this->get_service(0, $type);
        foreach ($data as $k => $v) {
            $data[$k]['children'] =  $this->get_service($v['id'], $type);
        }
        return $data;
    }

    /**
     * 获取服务设施
     * @param $pid
     * @param $type
     * @return array
     */
    private  function get_service($pid = 0, $type = "hotel")
    {
        $builder = DB::select(DB::expr('*,IFNULL(displayorder,9999) as real_displayorder'))
            ->from('hotel_service')
            ->where('pid', '=', $pid)
            ->and_where('isopen', '=', 1)
            ->and_where('is_belong_hotel', '=', $type == 'hotel' ? 1 : 0)
            ->order_by('real_displayorder', 'asc');

        return $builder->execute()->as_array();
    }

    /**
     * @function 获取日期内酒店房型最低价
     * @param $roomId
     * @param $startTime
     * @param $endTime
     * @return int
     */
    private  function get_room_mini_price($roomId, $startTime, $endTime)
    {


        $row = DB::select(array(DB::expr('MIN(price)'), 'price'))
            ->from('hotel_room_price')
            ->where('suitid', '=', $roomId)
            ->and_where('supplier_channel_id', '=', 1)
            ->and_where('price', '!=', 0)
            ->and_where('day', '>=', $startTime)
            ->and_where('day', '<', $endTime)
            ->and_where_open()
            ->where('number', '>', 0)
            ->or_where('number', '=', '-1')
            ->and_where_close()
            ->execute()
            ->current();

        if (!empty($row)) {
            $price = $row['price'] ? $row['price'] : 0;
        } else {
            $price = 0;
        }
        return $price;
    }

    /**
     * 格式化酒店每日价格数据
     * @param $data
     * @return mixed
     */
    private function make_day_price($data)
    {
        $now = strtotime(date('Y-m-d'));
        foreach ($data as &$row) {
            //过期数据
            if ($row['day'] < $now) {
                $row['adultprice'] = 0;
                $row['childprice'] = 0;
                $row['oldprice']   = 0;
            }
            $row['date']     = date('m-d', $row['day']);
            $row['daynum']   = (int)(date('d', $row['day']));
            $row['fulldate'] = date('Y-m-d', $row['day']);
            $row['digital']  = (int)(date('d', $row['day']));
            $row['weekday']  = Model_Api_V2_System::get_weekday($row['day']);
            $row['md_date']  = date('m月d日', $row['day']);
            $row['price']    = Currency_Tool::price($row['price']);
        }
        return $data;
    }

    /**
     * 格式化返回数据
     * @param $base_data
     * @return array[]
     */
    private  function format_day_price($base_data)
    {
        /*key替换为时间戳*/
        $arr = array();
        foreach($base_data as $v){
            $arr[$v['day']] = $v;
        }
        /*获取数组中最大和最小时间*/
        $first = reset($arr);
        $last = end($arr);
        $time_difference = ($last['day']-$first['day'])/86400;/*计算相差多少天*/
        /*循环判断缺少那天的报价，并插入缺少部分*/
        $data = array();
        for($i=0;$i<=$time_difference;$i++){
            $day = $first['day']+$i*86400;
            if($arr[$day]){
                $data[$i] = $arr[$day];
            }else{
                /*判断当前时间前一天是否有报价没有就不添加*/
                $day2 = $day-86400;
                if($arr[$day2]){
                    $data[$i] = array(
                        'date' => date('m-d',$day),
                        'day' => $day,
                        'daynum' => date('j',$day),
                        'digital' => date('j',$day),
                        'fulldate' => date('Y-m-d',$day),
                        'weekday' => Model_Api_V2_System::get_weekday($day),
                        'status' => 1
                    );
                }
            }
        }
        $par    = array(
            'date' => date('m-d',$last['day']+86400),
            'day' => $last['day']+86400,
            'daynum' => date('j',$last['day']+86400),
            'digital' => date('j',$last['day']+86400),
            'fulldate' => date('Y-m-d',$last['day']+86400),
            'weekday' => Model_Api_V2_System::get_weekday($last['day']+86400),
            'status' => 1
        );
        $data[] = $par;
        return array(
            'list' => $data
        );
    }

    /**
     * 获取指定的酒店信息
     * @param $id
     * @param $field
     * @return mixed|null
     */
    private function get_hotel($id, $field = '')
    {
        $field = $field ? DB::expr($field) : '*';
        return DB::select($field)
            ->from('hotel')
            ->where('id', '=', $id)
            ->execute()
            ->current();
    }

    /*
  * 属性生成where条件,用于多条件属性搜索.
  * */
    private function get_attr_where($attrid)
    {
        $arr = Common::remove_arr_empty(explode('_', $attrid));
        foreach ($arr as $value) {
            $value = intval($value);
            if ($value != 0) {
                $str .= " and FIND_IN_SET($value,sline_hotel.attrid) ";
            }
        }
        return $str;
    }

    /**
     * 获取酒店套餐
     * @param $params
     * @return Array
     */

    private function suit($productid)
    {
        $pay_name = array(
            '1' => '全款支付',
            '2' => '定金支付',
            '3' => '二次确认'
        );
        $fields = [
            'id',
            'hotelid',
            'roomname',
            'breakfirst',
            'computer',
            'roomstyle',
            'roomarea',
            'roomfloor',
            'roomwindow',
            'piclist',
            'jifencomment',
            'jifentprice',
            'jifenbook',
            'paytype',
            'dingjin',
            'description',
            'need_confirm',
            'pay_way',
            'auto_close_time',
            'limit_order',
            'litpic',
            'servicelist',
            'day_before',
            'hour_before',
            'minute_before',
            'refund_restriction',
            'people_limit',
            'bed_addable',
            'auto_confirm_time'
        ];
        $suit = DB::select_array($fields)->from('hotel_room')
            ->where("hotelid=:productid")
            ->order_by('displayorder', 'ASC')
            ->param(':productid', $productid)
            ->execute()
            ->as_array();

        foreach ($suit as &$r) {
            $r['title'] = $r['roomname'];
            unset($r['roomname']);
            $r['price'] = Model_Hotel::get_minprice($productid, $r['id']);
            $r['sellprice'] = Model_Hotel::get_sellprice($productid);//挂牌价
            $r['piclist'] = Product::pic_list($r['piclist']);
            foreach ($r['piclist'] as &$roompic) {
                $roompic = $this->img_url($roompic[0], 750, 400);
            }
            $time = DB::select('day')->from('hotel_room_price')->where("hotelid={$productid} and supplier_channel_id=1 and suitid={$r['id']} and number!=0 and day>=" . strtotime(date('Y-m-d')))->order_by('day',
                'asc')->execute()->current();
            $r['startTime'] = ! empty($time) ? $time['day'] : time();
            $r['endTime'] = strtotime('+1 day', $r['startTime']);
            $r['paytype_name'] = $pay_name[$r['paytype']];
            $r['description'] = $this->content_add_domain($r['description']);


        }
        return $suit;
    }

    /**
     * 获取详细内容
     * @param $params
     * @return array
     */
    private function get_detail_content($params)
    {

        $default = array(
            'typeid' => '2',
            'productinfo' => 0,
            'onlyrealfield' => 1,
            'pc' => 0

        );
        $params = array_merge($default, $params);
        extract($params, EXTR_OVERWRITE);
        $arr = DB::select()->from('hotel_content')
            ->where('webid', '=', 0)
            ->and_where('isopen', '=', 1)
            ->order_by('displayorder', 'ASC')
            ->execute()
            ->as_array();

        //扩展表数据
        $productid = $productinfo['id'];//产品id
        $ar = DB::select()->from('hotel_extend_field')->where('productid', '=', $productid)->execute()->as_array();

        $list = array();
        foreach ($arr as $v) {
            if ($v['columnname'] == 'tupian') {
                continue;
            }
            $content = '';
            if ($v['isrealfield'] == 1) {
                $content = ! empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
                $content = $content ? $content : '';
            }
            if (empty($content)) {
                continue;
            }

            $a = array();
            $a['columnname'] = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];
            if ($v['columnname'] == 'jieshao' && $productinfo['isstyle'] == 1) {
                $content = $productinfo['jieshao'];
                if (empty($content)) {
                    continue;
                }
                $a['is_array'] = 0;

            }
            $a['content'] = $this->content_add_domain($content);
            $list[] = $a;

        }
        return $list;
    }

    /**
     * 格式化酒店详情
     * @param $data
     * @return mixed
     */
    private function format_detail($data)
    {
        if ( ! empty($data['servicelist'])) {
            $data['hservicelist'] = Model_Hotel_Service::get_product_service_tree_data($data['id']);
        }

        $data['product_video'] = $data['product_video'] ? $this->img_url((explode('|',
            $data['product_video'])[0])) : '';

        if($data['supplierlist']) {
            $supplier_shop_service = new Service_Api_Supplier_Shop();
            $data['suppliers'] = $supplier_shop_service->get_shop_info($data['supplierlist']);
            if ( ! $data['suppliers']) {
                $data['supplierlist'] = null;
            }
        }

        //获得积分策略
        $jifenprice_info = Model_Jifen_Price::get_used_jifentprice($data['jifentprice_id'], self::TYPE_ID);
        $data['jifentprice_info'] = $this->filter_data(array('isopen', 'id', 'toplimit', 'jifentprice'), $jifenprice_info);
        $jifenbook_info = Model_Jifen::get_used_jifenbook($data['jifenbook_id'], self::TYPE_ID);
        $data['jifenbook_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifenbook_info);
        $jifencomment_info = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
        $data['jifencomment_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifencomment_info);
        $data['rank_name'] = $data['hotelrankid'] ? $this->get_rank_name($data['hotelrankid']) : '';

        return $data;
    }

    /**
     * 获取星级名称
     * @param $rank_id
     * @return mixed
     */
    private function get_rank_name($rank_id)
    {
        if(!$rank_id){
            return null;
        }
        return DB::select()
            ->from('hotel_rank')
            ->where('id', '=', $rank_id)
            ->execute()
            ->get('hotelrank');
    }

    /**
     * 获取按天的日期范围内的价格
     * @param $suit_id
     * @param $start_time
     * @param $end_time
     * @param $row
     * @return array
     */
    private function get_day_price($suit_id, $start_time, $end_time, $row = null)
    {
        $query = DB::select()->from('hotel_room_price')
            ->where('suitid', '=', $suit_id);
        $start = strtotime($start_time);
        $end   = strtotime($end_time);
        $query->and_where('day', '>=', $start);
        $query->and_where('day', '<=', $end);
        if ($row) {
            $query->limit($row);
        }
        return $query->execute()->as_array();
    }
    /**
     * 获取星级列表
     * @return array
     */
    private  function get_ranks()
    {
        return DB::select('id','hotelrank')
            ->from('hotel_rank')
            ->where('webid', '=', 0)
            ->order_by('orderid', 'ASC')
            ->execute()
            ->as_array();
    }

    /**
     * 获取价格列表
     * @return array
     */
    private  function get_prices()
    {
        $data = DB::select('id','min','max')
            ->from('hotel_pricelist')
            ->where('webid', '=', 0)
            ->execute()
            ->as_array();
        foreach ($data as &$row) {
            if ($row['min'] != '' && $row['min'] != 0 && $row['max'] != '' && $row['max'] != 0) {
                $row['name'] =  $row['min'] . '-' . $row['max'];
            } else if ($row['min'] == '' || $row['min'] == 0) {
                $row['name'] =  $row['max'] . '以下';
            } else if ($row['max'] == '' || $row['max'] == 0) {
                $row['name'] =  $row['min'] . '以上';
            }
        }
        return $data;
    }

    /**
     * 获取属性列表
     * @return array
     */
    private  function get_attributes()
    {
        $data = self::get_attribute_by_pid();
        foreach ($data as &$item) {
            $item['child'] = self::get_attribute_by_pid($item['id']);
        }
        return $data;
    }

    /**
     * 通过父级id获取属性
     * @param $pid
     * @return array
     */
    private function get_attribute_by_pid($pid = 0)
    {
        return DB::select('id', array('attrname', 'name'))
            ->from('hotel_attr')
            ->where('pid', '=', $pid)
            ->and_where('isopen', '=', 1)
            ->order_by(DB::expr('IFNULL(displayorder,9999)'), 'asc')
            ->execute()
            ->as_array();
    }




}